<template>
  <BaseDialog
    :title="title"
    :handleCancel="handleCancel"
    :handleOk="handleOk"
    :width="iSarea ? '1200px' : '1200px'"
    v-model:dialogVisible="props.dialogVisible"
    :footer="true"
  >
    <div class="dialog__body">
      <div class="left">
        <div class="use_titile">选择片区/村社</div>
        <!-- <el-tabs
          v-else
          v-model="activeName"
          class="demo-tabs"
          @tab-change="handleChange"
        >
          <el-tab-pane label="按台区选择" :name="1"> </el-tab-pane>
          <el-tab-pane label="按小区选择" :name="2"> </el-tab-pane>
        </el-tabs> -->
        <!-- <BaseForm
          ref="searchForm"
          type="search-pop"
          :items="iSarea ? formItems2 : formItems"
          v-model:form="searchParams"
          @search="handleSearch"

        >
        </BaseForm> -->

        <el-form
          ref="ruleFormRef"
          :model="searchParams"
          style="padding: 16px 16px 0 16px"
          :inline="true"
          label-width="0px"
        >
          <el-form-item>
            <el-input
              style="width: 135px"
              v-model="searchParams.communityName"
              placeholder="请输入片区/村社名称"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="props.showManager">
            <el-select
              style="width: 135px"
              v-model="searchParams.managerId"
              filterable
              placeholder="请选择网格经理"
              clearable
            >
              <el-option
                v-for="item in optionsMange"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- v-if="props.showPower" -->
          <el-form-item v-if="props.showPower" >
            <selectPage
              :item="powerItem"
              :firstName="searchParams.powerName"
              v-model="searchParams.powerId"
              style="width: 135px"
              @update:modelValue="changePower"
            />
          </el-form-item>
          <!-- v-if="props.showLock" -->
          <el-form-item >
            <el-select
              style="width: 135px"
              v-model="searchParams.lockId"
              filterable
              placeholder="请选择开闭所" 
              @change="changeLock"
              clearable
            >
              <el-option
                v-for="item in lockList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <selectPage
              :item="lineItem"
              v-model="searchParams.lineId"
              :search="lineSearch"
              style="width: 135px"
              @update:modelValue="changeLine"
            />
          </el-form-item>
          <el-form-item>
            <selectPage
              :item="areaItem"
              v-model="searchParams.areaId"
              :search="areaSearch"
              style="width: 135px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon>
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button @click="resetForm">
              <el-icon>
                <RefreshLeft />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <!-- <el-checkbox :indeterminate="indeterminate" @change="changeAllCheck" v-model="checkAll">全选</el-checkbox>
        <el-scrollbar v-loading="loading" class="scrollBox" style="height: 320px; padding-left: 10px; padding-top: 10px">
          <div v-for="(n, i) in list" :key="i" style="">
            <el-checkbox v-model="n.checked" @change="onChange(n)">
              {{ iSarea ? n.communityName : n.communityName }}
            </el-checkbox>
          </div>
        </el-scrollbar> -->
        <el-table
          border
          ref="multipleTableRef"
          v-loading="loading"
          element-loading-text="加载中..."
          :data="list"
          height="320px"
          @select="handleSelectionChange"
          @select-all="selectAll"
          :row-key="getRowKeys"
        >
          <el-table-column
            :reserve-selection="true"
            type="selection"
            width="55"
          />
          <el-table-column
            prop="communityName"
            label="片区/村社名称"
            width="200px"
          />
          <el-table-column
            prop="address"
            label="供电单位"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ getPowerName(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="供电线路"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ getLineName(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="台区" show-overflow-tooltip>
            <template #default="scope">
              {{ getAreaName(scope.row) }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="areaName" label="供电单位（供电线路）（台区）">
            <template #default="scope">
              <div style="margin-left: 2px; margin-right: 2px; margin-top: 5px"
                v-for="item in scope.row.communityAreaResDtoList" type="info" :key="`${item.powerId}-${item.lineId}`">
                <span v-if="getAddress(item).length < 16">{{
                  getAddress(item)
                }}</span>
                <el-tooltip v-else class="box-item" effect="dark" :content="getAddress(item)" placement="top">
                  <span class="text_ellipsis">{{ getAddress(item) }}</span>
                </el-tooltip>
              </div>
            </template>
          </el-table-column> -->
        </el-table>

        <Pages
          style="margin-top: 10px"
          v-model:page="page"
          :small="true"
          :getTableData="getTableData"
        ></Pages>
      </div>
      <div class="right">
        <div class="use_titile">已选择</div>
        <SelectList
          :iSarea="iSarea"
          :filterList="filterList"
          v-model:selectList="selectList"
        />
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { basicConfigService } from "@/api/basicConfig";
import selectPage from "../selectPage.vue";
import SelectList from "./selectList.vue";
import CorrelationCommunity from "./correlationCommunity.vue";
import { commonService } from "@/api/common";
import { ElTable } from "element-plus";
import { powerService } from "@/api/power";
import { lineService } from "@/api/line";
import { lockService } from "@/api/lock";

const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  showManager: {
    type: Boolean,
    default: true,
  },
  showPower: {
    type: Boolean,
    default: true,
  },
  showLock: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
  },
  type: {
    type: Number,
  },
  communityDtoList: {
    type: Array,
  },
});
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
let list = reactive([]);
const checkAll = ref(false);
// 控制全选状态
// const indeterminate = computed(() => {
//   const checkedCount = list.filter((e) => e.checked).length
//   checkAll.value = checkedCount !== 0 && checkedCount === list.length
//   return checkedCount > 0 && checkedCount < list.length
// })
// const multipleSelection = ref([])
const handleSelectionChange = (rows, row) => {
  console.log(rows, row);
  if (rows.findIndex((e) => e.communityId === row.communityId) > -1) {
    selectList.value.push(row);
  } else {
    let key = "communityId";
    selectList.value = selectList.value.filter((v) => v[key] != row[key]);
  }
};
const selectAll = (rows) => {
  // let key = iSarea.value ? 'areaId' : 'communityId'
  const key = "communityId";
  if (rows.length > 0) {
    const selectSet = selectList.value.map((item) => item[key]);
    list.forEach((item) => {
      if (!selectSet.includes(item[key])) selectList.value.push(item);
    });
  } else {
    list.forEach((item) => {
      for (let index = 0; index < selectList.value.length; index++) {
        if (selectList.value[index][key] == item[key]) {
          selectList.value.splice(index, 1);
        }
      }
    });
  }
};

const activeName = ref(1);
const lineIdList = ref([]);
const powerSupplyIdList = ref([]);
const iSarea = computed(() => props.type === 2);

const selectList = ref([...props.communityDtoList]);

const loading = ref(false);

const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const searchParams = ref({
  communityName: "",
  lineId: "",
  managerId: "",
  powerSupplyId: "",
  areaId: "",
  powerId: "",
  lockId: "",
  searchParams:'',
});

const powerItem = ref({
  name: "",
  key: "powerId",
  funName: "getByAreaQueryByPower",
  placeholder:'请选择供电单位',
  option: {
    name: "powerName",
    value: "powerId",
  },
});
const lineSearch = ref({
  powerId: searchParams.value.powerId,
});
const lineItem = ref({
  name: "供电线路",
  key: "lineId",
  placeholder:'请选择供电线路',
  funName: "getByAreaQueryByLine",
  option: {
    name: "lineName",
    value: "lineId",
  },
});
const areaSearch = ref({
  powerId: searchParams.value.powerId,
  lineId: searchParams.value.lineId,
});
const areaItem = ref({
  name: "台区",
  key: "areaId",
  placeholder:'请选择供电单位',
  funName: "getByAreaQueryByArea",
  option: {
    name: "areaName",
    value: "areaId",
  },
});
const changePower = (val: any) => {
  lineSearch.value.powerId = val;
  areaSearch.value.powerId = val;
  searchParams.value.lineId = "";
  searchParams.value.areaId = "";
};
const changeLine = (val: any) => {
  areaSearch.value.lineId = val;
  searchParams.value.areaId = "";
};
const getPowerName = (row) => {
  let powerNames = row.communityAreaResDtoList?.map((n) => n.powerName);
  if (powerNames.length > 0) {
    return [...new Set(powerNames)].join("、");
  }
  return "";
};
const getLineName = (row) => {
  let lineNames = row.communityAreaResDtoList?.map((n) => n.lineName);
  if (lineNames.length > 0) {
    return [...new Set(lineNames)].join("、");
  }
  return "";
};
const getAreaName = (row) => {
  let areaName = row.communityAreaResDtoList?.map((n) => n.areaName);
  if (areaName.length > 0) {
    return [...new Set(areaName)].join("、");
  }
  return "";
};

const getTableData = async (e) => {
  let data = {
    data: {
      ...searchParams.value,
    },
    pageSize: page.pageSize,
    pageNumber: page.currentPage,
  };
  list = [];
  loading.value = true;
  try {
    let res;
    res = await basicConfigService.pageListCommunityResDto(data);
    list = res.data.content;
    page.total = res.data.total * 1;
    // filterList(iSarea.value ? 'areaId' : 'communityId')
    filterList();
    loading.value = false;
  } catch (error) {
    loading.value = false;
    list = [];
  }
};
const filterList = () => {
  // if (key == 'areaId') selectCommunity.value = []
  const key = "communityId";
  nextTick(() => {
    multipleTableRef.value!.clearSelection();
  });
  list.forEach((row) => {
    if (selectList.value.findIndex((v) => row[key] == v[key]) > -1) {
      console.log(1000);
      nextTick(() => {
        multipleTableRef.value!.toggleRowSelection(row, true);
      });
    }
  });
};
const handleSearch = () => {
  page.currentPage = 1;
  getTableData(activeName.value);
};

// const onChange = (e) => {
//   if (e.checked) {
//     selectList.value.push(e)
//   } else {
//     let key = iSarea.value ? 'areaId' : 'communityId'
//     selectList.value = selectList.value.filter((v) => v[key] != e[key])
//   }
// }
const emit = defineEmits(["update:dialogVisible", "update:communityDtoList"]);
const handleOk = (data) => {
  // if (iSarea.value) {
  //   let data = CorrelationCommunityRef.value.associationCommunityList
  //   emit('update:communityDtoList', data)
  // } else {
  //   emit('update:communityDtoList', selectList.value)
  // }
  emit("update:communityDtoList", selectList.value);
  handleCancel();
};

const handleCancel = () => {
  emit("update:dialogVisible", false);
};
const optionsMange = ref([]);
const getAllManager = () => {
  basicConfigService.getAllManager({ data: {} }).then((res) => {
    optionsMange.value = res.data.map((n) => {
      return {
        label: n.managerName,
        value: n.managerId,
      };
    });
  });
};
onMounted(() => {
  if(props.item.powerId){
    searchParams.value.powerId=props.item.powerId;
    searchParams.value.powerName=props.item.powerName
  }
  getTableData(activeName.value);
  /* if (props.type === 2) {
    getSearchSelectList()
  } */
  getLockList();
  // getPowerList();
  //getLineList()
  //getAreaList()
  getAllManager();
});
const resetForm = () => {
  searchParams.value = {
    communityName: "",
    lineId: "",
    managerId: "",
    powerSupplyId: "",
    areaId: "",
    powerId: "",
    lockId: "",
    searchParams:'',
  };
  lineSearch.value.powerId = ""
  areaSearch.value.powerId = ""
  areaSearch.value.lineId = ""
  getTableData(activeName.value);
  // getLineList();
  // getAreaList();
};
const getPowerList = () => {
  basicConfigService.getByAreaQueryDto({ data: {} }).then((res) => {
    powerSupplyIdList.value = res.data.map((n) => {
      return {
        label: n.powerName,
        value: n.powerId,
      };
    });
    lineIdList.value = res.data.map((n) => {
      return {
        label: n.lineName,
        value: n.lineId,
      };
    });
    areaIdList.value = res.data.map((n) => {
      return {
        label: n.areaName,
        value: n.areaId,
      };
    });
  });
};
const lockList = ref([]);
const getLockList = () => {
  if (props.showLock) {
    lockService.getList({ data: {} }).then((res) => {
      lockList.value = res.data.map((n) => {
        return {
          label: n.lockName,
          value: n.lockId,
        };
      });
    });
  }
};
const getLineList = () => {
  basicConfigService
    .getByAreaQueryDto({
      data: {
        powerId: searchParams.value.powerId,
        lockId: searchParams.value.lockId,
      },
    })
    .then((res) => {
      lineIdList.value = res.data.map((n) => {
        return {
          label: n.lineName,
          value: n.lineId,
        };
      });
    });
};
const areaIdList = ref([]);
const getAreaList = () => {
  basicConfigService
    .getByAreaQueryDto({
      data: {
        powerId: searchParams.value.powerId,
        lineId: searchParams.value.lineId,
        lockId: searchParams.value.lockId,
      },
    })
    .then((res) => {
      areaIdList.value = res.data.map((e) => {
        return {
          label: e.areaName,
          value: e.areaId,
        };
      });
    });
};
// const changePower = () => {
//   if (searchParams.value.powerId) {
//     searchParams.value.lineId = "";
//     searchParams.value.areaId = "";
//   }
//   getLineList();
//   getAreaList();
// };
const changeLock = () => {
  if (searchParams.value.lockId) {
    searchParams.value.lineId = "";
    searchParams.value.areaId = "";
  }
  // getLineList();
  // getAreaList();
};
// const changeLine = () => {
//   if (searchParams.value.lineId) {
//     searchParams.value.areaId = "";
//   }
//   getAreaList();
// };
const getAddress = (row) => {
  return `${row.powerName}（ ${row.lineName} ）（ ${row.areaName} ）`;
};
const getRowKeys = (row) => {
  return row.communityId;
};
</script>
<style lang="scss" scoped>
.dialog__body {
  display: flex;

  .left {
    width: 900px;

    :deep(.el-form--inline .el-form-item) {
      margin-right: 5px;
    }
  }

  .right {
    flex: 1;
    width: 0;
    border-left: 1px solid #ccc;
    padding-left: 10px;
  }
}
</style>
